<?php

class DayuhaoUtil {

    /**
     * 上传图片到大鱼号
     * @param string $picPath
     * @param string $cookie
     * @param int $file_size 文件大小
     */
    public static function upload($picPath, $cookie) {
        $pInfo = pathinfo($picPath);
        $post_data['id'] = 'WU_FILE_1';
        $post_data['name'] = $pInfo['filename'] . '.jpg';
        $post_data['type'] = 'image/jpeg';
        $post_data['lastModifiedDate'] = date('D M d Y h:i:s e O');
        $post_data['size'] = filesize($picPath);
        $post_data['upfile'] = new CURLFile($picPath);
        $url = "https://ns.dayu.com/article/imageUpload?appid=website&fromMaterial=0&wmid=c4e3c5221d0c4254b2771048de1a52d0&wmname=%E4%B8%80%E8%B5%B7%E7%9C%8B%E8%88%AA%E6%8B%8D&sign=374c4de9037c9f303a9569321e4ce2f7";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书  
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 检查证书中是否设置域名
        // 本地测试代理 @TODO 上线需注释掉
//        curl_setopt($ch, CURLOPT_PROXY, '192.168.50.98');
//        curl_setopt($ch, CURLOPT_PROXYPORT, '8888');

        //multipart 方式上传需要注意传递的参数是数组，不是字符串
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output = curl_exec($ch);
        curl_close($ch);
        if ($output) {
            $result = json_decode($output, true);
            $res = isset($result['data']['imgInfo']) ? $result['data']['imgInfo'] : [];
            return $res;
        } else {
            return [];
        }
    }

    /**
     * 根据图片链接上传图床
     * @param string $picUrl
     * @param string $cookie
     * @return string
     */
    public static function uploadByUrl($picUrl, $cookie) {
        $path = '/usr/share/nginx/html/cron/res/images/nav/';
        if (ENVIRONMENT == 'development') {
            $path = APPPATH . '../res/images/nav/';
        }

        $filePath = $path . uniqid() . '.jpg';
        if (!file_exists($path)) {
            mkdir($path);
            chmod($path, 755);
        }

        $file = @file_get_contents($picUrl);
        if (empty($file)) {
            return [];
        }

        file_put_contents($filePath, $file);
        if (file_exists($filePath)) {
            $res = self::upload($filePath, $cookie);
            @unlink($filePath);
            return $res;
        } else {
            return [];
        }
    }

}
